package com.logos.ruralrevitalization.interceptor;

import com.logos.ruralrevitalization.exception.UnauthorizedException;
import com.logos.ruralrevitalization.utils.JwtPlusTool;
import com.logos.ruralrevitalization.utils.LoginContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;


@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtPlusTool jwtPlusTool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("logos ")) {
            log.error("token:{}",token);
            throw new UnauthorizedException("未找到有效的Token");
        }

        // 去掉logos前缀
        token = token.substring(6);

//        try {
//            // 解析Token并获取其中的用户信息
//            Map<String, Object> claims = jwtTool.parseToken(token);
//
//            // 检查解析结果是否为空或缺少必要字段
//            if (claims == null || !claims.containsKey("loginPhone")) {
//                throw new UnauthorizedException("Token解析失败，缺少必要字段");
//            }
//
//            // 设置登录上下文
//            LoginContextHolder.set("loginPhone", claims.get("loginPhone"));
//
//        } catch (ExpiredJwtException e) {
//            // 处理Token过期的情况
//            throw new UnauthorizedException("Token已过期", e);
//        } catch (SignatureException e) {
//            // 处理签名无效的情况
//            throw new UnauthorizedException("Token签名无效", e);
//        } catch (Exception e) {
//            // 处理其他异常
//            throw new UnauthorizedException("无效的Token", e);
//        }
//
//        // 如果Token解析成功，则继续处理请求
//        return true;

        try {
            // 验证Token
            String userId = jwtPlusTool.parseToken(token);
            LoginContextHolder.set("loginId", userId);
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            throw new UnauthorizedException("无效的Token", e);
        }

        // Token验证通过，继续处理请求
        // 将token的值传递给后续的请求处理
        return true;
    }
}
